//
//  FPView.swift
//  TLCLockDemo
//
//  Created by run on 2024/7/16.
//

import AlertToast
import Combine
import SwiftUI
import TLCLock

class FpModel: SheetModel {
    var cancellable: AnyCancellable?
    let device: LockDevice

    init(device: LockDevice) {
        self.device = device
    }

    deinit {
        cancellable?.cancel()
        debugPrint("fp model deinit")
    }
}

struct FpView: View {
    let model: FpModel
    

    @State var id: String = ""
    
    @State var forver: Bool = true
    @State var begin: Date = .init()
    @State var end: Date = Date().nextYear

    var body: some View {
        VStack {
            Text(model.device.macAddress)
                .bold()
                .foregroundColor(.orange)
                .font(.headline)
                .padding(.horizontal, 20)
                .frame(maxWidth: .infinity, alignment: .center)
            
            YxrInputView("指纹ID", text: $id)
            YxrToggleView(title: "永久", isOn: $forver)
            if !forver {
                YxrDatePicker(title: "开始时间", date: $begin)
                YxrDatePicker(title: "结束时间", date: $end)
            }
            
            YxrActionView(
                data: [
                    (0, "添加指纹"),
                    (1, "删除指纹"),
                    (2, "更新时间"),
                    (3, "冻结指纹"),
                    (4, "解冻指纹"),
                    (5, "清空指纹"),
                ],
                itemBuilder: { value in
                    YXRActionItem(text: value.1) {
                        switch value.0 {
                        case 0: startAddFp()
                        case 1: deleteFp()
                        case 2: modifyFp()
                        case 3: updateFp(state: .frozen)
                        case 4: updateFp(state: .effective)
                        case 5: clearFp()
                        default:
                            showToast("未实现的方法")
                        }
                    }
                }
            ).padding(.all, 10)
            
            LogView()
        }
        .yxrNavigationTitle("Fp")
    }

    func startAddFp() {
        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }
        
        let from: Date? = forver ? nil : begin
        let to: Date? = forver ? nil : end

        Task {
            showLoading()
            let result = await model.device.addFp(begin: from, end: to, lockKey: lockKey, trackId: Server.testTrackId) {
                offset, _, maxNum in
                if offset != maxNum {
                    showLoading("请录入指纹: \(offset + 1)")
                }
            }
            hideLoading()

            if result.isFailure {
                showToast(result.errorMessage)
                return
            }
            self.id = "\(result.value!)"
            showToast("录入成功")
            Log.info("指纹id：\(self.id)")
        }
    }

    func deleteFp() {
        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }

        guard let idx = UInt32(id) else {
            showToast("id 错误")
            return
        }

        lockTask(desc: "deleteFp") {
            await model.device.deleteFingerprint(fpId: idx, lockKey: lockKey, trackId: Server.testTrackId)
        }
    }

    func updateFp(state: FingerprintState) {
        guard let idx = UInt32(id) else {
            showToast("id 错误")
            return
        }

        let desc = state == .frozen ? "冻结" : "解冻"

        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }

        lockTask(desc: "\(desc) Fp") {
            await model.device.changeFingerprintState(fpId: idx, state: state, lockKey: lockKey, trackId: Server.testTrackId)
        }
    }

    func modifyFp() {
        guard let idx = UInt32(id) else {
            showToast("id 错误")
            return
        }

        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }
        
        let from: Date? = forver ? nil : begin
        let to: Date? = forver ? nil : end

        lockTask(desc: "modify") {
            await model.device.modifyFingerprint(fpId: idx, begin: from, end: to, lockKey: lockKey, trackId: Server.testTrackId)
        }
    }

    func clearFp() {
        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }

        lockTask(desc: "modify") {
            await model.device.clearAllFingerprint(lockKey: lockKey, trackId: Server.testTrackId)
        }
    }
}
